package com.lv.xulin.demopro;

import android.app.Activity;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lv.adapter.RvLinkManAdapter;
import com.lv.db.control.DBControl;
import com.lv.db.dao.LinkManDao;
import com.lv.db.dao.LinkManDaoImpl;
import com.lv.db.entity.LinkMan;
import com.lv.tools.view.XRecyclerView;
import com.lv.tools.view.XSideBar;
import com.lv.utils.CharacterParser;
import com.lv.utils.L;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 应用此类，一定要获得通讯录权限。
 * 应用此类，一定要获得通讯录权限。
 * 应用此类，一定要获得通讯录权限。
 */
public class LinkmanActivity extends Activity {
    private final String TAG = this.getClass().getSimpleName().toString();

    private Map<String, Object> bakMap = null;

    private TextView tvAdd, tvEdit, tvDel;
    private EditText etSearch;
    private XSideBar sideBarPinyin;
    private XRecyclerView xRecyclerView;
    private RvLinkManAdapter mAdapter;//适配器
    private RelativeLayout rltBottom;
    private TextView tvCheckedCount;
    private Button btnSubmit;
    private LinkManDao linkManDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linkman);

/*  插入测试数据

        try {
            LinkManager linkManager=new LinkManager(this);

            for (int i=1000;i<2000;i++){
                linkManager.addContacts("测:"+i ,"1531231"+i,"f"+i+"@163.com");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
*/

        tvAdd = (TextView) findViewById(R.id.tvAdd);
        tvEdit = (TextView) findViewById(R.id.tvEdit);
        tvDel = (TextView) findViewById(R.id.tvDel);


        long st1 = System.currentTimeMillis();
        //创建联系人数据表
        DBControl dbControl = new DBControl(this);
        dbControl.create_system_table();

        //获得本地联系人
        linkManDao = new LinkManDaoImpl(this);
        bakMap = linkManDao.getAll();

        if (bakMap == null || bakMap.size() == 0) {
            //如果本本地联系人不存在记录，则查询通讯簿
            bakMap = getBakMap();

            //插入到APP数据库备份
            List<LinkMan> list = new ArrayList<>();
            for (Map.Entry<String, Object> map1 : bakMap.entrySet()) {
                LinkMan linkMan = JSON.parseObject(map1.getValue().toString(), LinkMan.class);
                linkMan.setFstate("0");//初始数据
                linkMan.setFspelledall(CharacterParser.getInstance().getSelling(linkMan.getFname()));
                String sortString = linkMan.getFspelledall().substring(0, 1).toUpperCase();
                linkMan.setFspellsort(sortString);
                list.add(linkMan);
            }
            linkManDao.add(list);
        }

        long st2 = System.currentTimeMillis();
        System.out.println("耗时是: " + (st2 - st1));
        //注册监听器
        registerContentObservers();

        //对比差异
        onChangeLinkMan(bakMap);

        //加载数据到list
        List<LinkMan> list = linkManDao.find(new HashMap<String, Object>());
        //显示联系人
        showLinkMan(list);

        //加载默认状态
        checkState();
    }

    private void showLinkMan(List<LinkMan> list) {
        etSearch = (EditText) findViewById(R.id.etSearch);
        tvCheckedCount = (TextView) findViewById(R.id.tvCheckedCount);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        rltBottom =(RelativeLayout) findViewById(R.id.rltBottom);

        //显示数据 RecyclerView
        xRecyclerView = (XRecyclerView) findViewById(R.id.rvLinkman);
        mLinearLayoutManager = new LinearLayoutManager(LinkmanActivity.this);
        xRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new RvLinkManAdapter(LinkmanActivity.this, list, R.layout.item_linkman_list, true);
        xRecyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        mAdapter.setOnRvItemClickLitener(new RvLinkManAdapter.OnRvItemClickLitener() {
            @Override
            public void onItemClick(View v, int position) {
                checkState();
            }

            @Override
            public void onItemLongClick(View v, int position) {
                for (LinkMan man : mAdapter.getChecked()) {
                    Log.i(TAG, man.getFphone());
                }

            }
        });

        //查看选中人
        tvCheckedCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LinkmanActivity.this,LinkmanCheckedListActivity.class);
                intent.putExtra("checkedMan",  JSONArray.toJSONString(mAdapter.getChecked().toArray()));
                startActivityForResult(intent,1);
            }
        });

        //侧边搜索栏
        sideBarPinyin = (XSideBar) findViewById(R.id.sideBarPinyin);
        sideBarPinyin.setTextView(((TextView) findViewById(R.id.dialog)));
        sideBarPinyin.OnLetterChangeListener(new XSideBar.OnLetterChangeListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    scrollToPosition(position);
                }
            }
        });


    }

    private void checkState() {
        int cklength = mAdapter.getChecked().size();
        int count = mAdapter.getItemCount();
        tvCheckedCount.setText("已选择:" + cklength + "人");
        btnSubmit.setText("确定(" + cklength + "/" + count + ")");
    }


    private void onChangeLinkMan(Map<String, Object> bakMap) {
        Map<String, Object> changeMap1 = getChangeMap();
        Map<String, Object> changeMap2 = getChangeMap();

        Map<String, Object> editMap = getEditMap(changeMap1, bakMap);
        Map<String, Object> addMap = getAddMap(changeMap1, bakMap);
        Map<String, Object> delMap = getDelMap(changeMap2, bakMap);

        String editstr = "";
        for (Map.Entry<String, Object> map : editMap.entrySet()) {
            editstr = editstr + map.getValue().toString() + ";";
            Log.i(TAG, "这是改变的手机号:" + map.getValue().toString());
            LinkMan linkMan = JSON.parseObject(map.getValue().toString(), LinkMan.class);
            linkManDao.updateByContactId(linkMan);
        }

        String addstr = "";
        List<LinkMan> list = new ArrayList<>();
        for (Map.Entry<String, Object> map : addMap.entrySet()) {
            addstr = addstr + map.getValue().toString() + ";";
            Log.i(TAG, "这是新增的手机号:" + map.getValue().toString());
            LinkMan linkMan = JSON.parseObject(map.getValue().toString(), LinkMan.class);
            linkMan.setFstate("0");
            list.add(linkMan);
        }
        linkManDao.add(list);

        String delstr = "";
        for (Map.Entry<String, Object> map : delMap.entrySet()) {
            delstr = delstr + map.getKey() + ";";
            Log.i(TAG, "这是删除的key:" + map.getKey() + " > val:" + map.getValue());
            LinkMan linkMan = JSON.parseObject(map.getValue().toString(), LinkMan.class);
            linkManDao.deleteByContactId(linkMan);

        }

        tvAdd.setText("add:" + addstr);
        tvEdit.setText("edit:" + editstr);
        tvDel.setText("del:" + delstr);


        //重新备份上一版本数据
        bakMap = getBakMap();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    private void registerContentObservers() {
        //注册一个监听数据库的监听器
        this.getContentResolver().registerContentObserver(RawContacts.CONTENT_URI, false, new ContentObserver(new Handler()) {
            @Override
            public boolean deliverSelfNotifications() {
                return super.deliverSelfNotifications();
            }

            @Override
            public void onChange(boolean selfChange) {

            }


            @Override
            public void onChange(boolean selfChange, Uri uri) {
                onChangeLinkMan(getBakMap());
            }
        });

    }

    private Map<String, Object> getDelMap(Map<String, Object> changeMap, Map<String, Object> bakMap) {
        Map<String, Object> delMap = new HashMap<>();
        for (Map.Entry<String, Object> map : changeMap.entrySet()) {
            String m1key = map.getKey();
            if (bakMap.get(m1key) != null) {
                bakMap.remove(m1key);
            }
        }
        if (bakMap.size() > 0) {
            for (Map.Entry<String, Object> map : bakMap.entrySet()) {
                delMap.put(map.getKey(), map.getValue().toString());
            }
        }
        return delMap;
    }


    private Map<String, Object> getAddMap(Map<String, Object> changeMap, Map<String, Object> bakMap) {
        Map<String, Object> addMap = new HashMap<>();
        for (Map.Entry<String, Object> map : bakMap.entrySet()) {
            String m1key = map.getKey();
            if (changeMap.get(m1key) != null) {
                changeMap.remove(m1key);
            }
        }
        if (changeMap.size() > 0) {
            for (Map.Entry<String, Object> map : changeMap.entrySet()) {
                addMap.put(map.getKey(), map.getValue().toString());
            }
        }
        return addMap;
    }

    private Map<String, Object> getEditMap(Map<String, Object> changeMap, Map<String, Object> bakMap) {
        Map<String, Object> editMap = new HashMap<>();

        for (Map.Entry<String, Object> map : bakMap.entrySet()) {
            String m1key = map.getKey();
            String m1val = map.getValue() == null ? "" : map.getValue().toString();
            if (changeMap.get(m1key) != null) {
                String changeVal = changeMap.get(m1key).toString();
                if (!m1val.equals(changeVal)) {
                    editMap.put(m1key, changeVal);
                }
            }
        }
        return editMap;
    }


    //获得备份的数据集
    private Map<String, Object> getBakMap() {
        Map<String, Object> baseMap = null;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] args = new String[]{"sort_key", "display_name", "contact_id", "data1"};
        try {
            Cursor cursor = getContentResolver().query(uri
                    , args
                    , null
                    , null
                    , args[0] + " asc ");
            baseMap = new HashMap<String, Object>();
            if (cursor.moveToNext()) {
                do {
                    String contact_phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String name = cursor.getString(cursor.getColumnIndex("display_name"));
                    int contact_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    if (name.length() > 8) {
                        name = name.substring(0, 8);
                    }
                    contact_phone = contact_phone.trim().replace(" ", "").replace("+86", "");
                    contact_phone = contact_phone.replace("+", "");
                    //联系人信息
                    LinkMan linkMan = new LinkMan();
                    linkMan.setFname(name);
                    linkMan.setFcontactid(String.valueOf(contact_id));
                    linkMan.setFphone(contact_phone);
                    baseMap.put(String.valueOf(contact_id), JSON.toJSONString(linkMan));
                } while (cursor.moveToNext());
            }
            cursor.close();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return baseMap;
    }

    //获得修改后的数据集
    private Map<String, Object> getChangeMap() {
        Map<String, Object> changeMap = null;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] args = new String[]{"sort_key", "display_name", "contact_id", "data1"};
        try {
            Cursor cursor = getContentResolver().query(uri
                    , args
                    , null
                    , null
                    , args[0] + " asc ");
            changeMap = new HashMap();
            if (cursor.moveToNext()) {
                do {
                    String contact_phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String name = cursor.getString(cursor.getColumnIndex("display_name"));
                    int contact_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    if (name.length() > 8) {
                        name = name.substring(0, 8);
                    }
                    contact_phone = contact_phone.trim().replace(" ", "").replace("+86", "");
                    contact_phone = contact_phone.replace("+", "");
                    //联系人信息
                    LinkMan linkMan = new LinkMan();
                    linkMan.setFname(name);
                    linkMan.setFcontactid(String.valueOf(contact_id));
                    linkMan.setFphone(contact_phone);
                    changeMap.put(String.valueOf(contact_id), JSON.toJSONString(linkMan));
                } while (cursor.moveToNext());
            }
            cursor.close();
        } catch (Exception e) {
            L.e(TAG, e.toString());
        }
        return changeMap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(data!=null){
                String removeList=data.getStringExtra("removeList");
                List<LinkMan> list=JSONArray.parseArray(removeList,LinkMan.class);
                mAdapter.removeChecked(list);
                mAdapter.notifyDataSetChanged();
                //加载默认状态
                checkState();
            }
        }
    }

    private LinearLayoutManager mLinearLayoutManager;

    private void scrollToPosition(int n) {
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            xRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = xRecyclerView.getChildAt(n - firstItem).getTop();
            xRecyclerView.smoothScrollBy(0, top);
        } else {
            xRecyclerView.scrollToPosition(n);
        }
    }

}